/**
 * 小程序-设计器 
 * @date 2019年8月22日
 * @author liu
 */

import Top from "@/components/top";
import DialogModel from "@/components/DialogModel.vue";
import {Chrome} from 'vue-color'
import { VueCropper } from 'vue-cropper'

import SVG from 'svg.js'
import {
    getTransform,
    getPointAndOpposite,
    getNewRect,
    dataURLtoBlob
} from '@/assets/js/commonJS.js'

export default {
    name: "home",
    components: {
        Top,
        DialogModel,
        Chrome,
        VueCropper
    },
    data() {
        return {
            designModel: false, // 设计模式(未创建改模版,设计记录模板)
            port: { // base端口
                ossPath: aly_config.IMG + '/',
                nodeUrl: aly_config.NODE,
                productThumbnail: aly_config.NODE + '/svgtopng', // 生成缩略图地址
                team: null,
                token: null,
                d: null, // 模板编号
            },
            RGBA: ['#fff', '#FFFFFF', '#FDD0A7', '#D0FECF', '#DDB5FF', '#6FCEFC', '#FEE6E6', '#AFDBB9', '#E6E0A0'],
            RGB: ['#000', '#C4C4C4', '#FDA005', '#41BD3E', '#B05EFF', '#3A9FFB', '#D96D6B', '#72B581', '#CFA972'],
            display: false, // 加载
            dialogOpen: false, // 对话框开关
            bgToggle: true, //修改背景图片颜色切换开关
            familyList: [], // 字体列表
            textToggle: "content", // 文字面板切换
            textSize: 0, // 文字大小
            saveTemplateBtn: false, // 保存模板
            toolType: "all",
            draw: null, // 画布
            templateInfo: null, // 存储模板数据
            pages: [], // 页面数据存储
            pageNum: 0, // 当前展示的页面下标
            codeBox: { // 选中元素的位置和大小
                x: 0,
                y: 0,
                width: 0,
                height: 0,
                isShow: false,
                rotate: 0
            },
            elementChecked: null, // 选中svg元素
            recordCodeBox: null, // 记录下codebox的之前的位置
            record: null, // 记录手指按下的信息
            addTextContent: '', // 添加的文字内容
            activeTextContent: '', // 选中的文字内容
            textObj: {}, // 选中文字属性对象
            setTextAttr: false, // 显示文字不是path
            replaceImg: false, // 更换图片开关
            materialTypes: [], // 图片分类
            materialTypesList: [], // 图片分类的图片数组
            matterParams: { // 素材分页
                TypeNum: null,
                TypeCategoryNum: 0,
                pageIndex: 1,
                pageSize: 10,
                more: true
            },
            materialTypesIndex: 0, // 图片分类下标
            bgImages: [], // 背景图片列表
            bgparams: { // 背景筛选
                pageIndex: 1,
                pageSize: 10,
                more: true
            },
            bgColor: '#fff',
            colorPicker: { // 调色盘
                show: false,
                color: '#745BFF',
                type: '', 
            },
            imgPicker: { // 图片选择
                show: false,
                type: ''
            },
            oldElemt: { // 记录最开始的元素
                bg: {
                    old: null,
                    replace: null
                },
            },
            operationType: '', // 操作类型
            oldimg: { // 图片的操作
                old: null,
                replace: null
            },
            addList: [], // 添加的元素
            svgFillIndex: 0, // 选中svg,修改拾取颜色的下标
            svgFillList: [], // 拾取的svg颜色列表
            redoList: [], // 可撤销列表
            undoList: [],// 可恢复list表
            activeImg: '', // 选中的图片
            clipImageBtn: false, // 裁剪图片开关
            errMsg: [],
            model: null, //刀版
        };
    },
    computed: {
        textTitle() {
            // 切换文字title
            let title = "";
            switch (this.textToggle) {
                case "lock":
                    title = "";
                    break;
                case "content":
                    title = "修改内容";
                    break;
                case "font":
                    title = "修改字体";
                    break;
                case "color":
                    title = "修改颜色";

                    break;
                case "size":
                    title = "修改大小";
                    this.setTextAttr = true;
                    break;
                case "align":
                    title = "修改对齐方式";
                    break;
                case "style":
                    title = "修改样式";
                    break;
            }
            return title;
        },
        fontStyle() {
            let style = `font-size: ${this.textObj.size}px;font-family: ${this.textObj.family};color: ${this.textObj.fill || '#000'}`
            return style
        },
        // 换算选中元素的位置大小为HTML元素
        codeBoxComputed() {
            // console.log(this.codeBox)
            // console.log(Math.abs(this.codeBox.height) + 'px', '计算')
            let style = `left: ${this.codeBox.x}px; top: ${this.codeBox.y}px;width: ${Math.abs(this.codeBox.width)}px;height: ${Math.abs(this.codeBox.height)}px; transform: rotate(${this.codeBox.rotate}deg);display: ${this.codeBox.isShow ? 'block' : 'none'};`
            // console.log(style)
            // this.$refs.box && (this.$refs.box.style.height = Math.abs(this.codeBox.height) + 'px')
            return style

        },

        todo() { // 是否可撤销或可恢复
            let redo = this.redoList.length > 0 ? true : false;
            let undo = this.undoList.length > 0 ? true : false;
            return {redo , undo}
        }
    },
    watch: {
        "colorPicker.color" : function(val) { // 调色盘颜色的变化
            // console.log(val.hex)
        }
    },
    created() {
        this.$axios.defaults.baseURL = aly_config.API + '/api'
    },
    mounted() {
        this.getwx(); // 配置微信接口调用
        
        var query = this.$route.query;
        var {d, token, m, team} = query;
        this.port.token = token
        this.port.d = d;
        this.port.team = team;
        this.designModel = m == 1 ? true : this.designModel;

        this.$axios.defaults.headers.token = this.port.token;
        this.$cookie.set('token', this.port.token, 7)
        this.$cookie.set('team', this.port.team, 7)
        this.getIndex();

    },
    methods: {
        
        getIndex() { //  复制模板
            this.display = true;
            this.getFontList();
            this.getTemplate();
            this.getMaterialTypes();
            this.getBgList().then(data => {
                data && (this.bgImages = data.Data)
            });
        },
        getTemplate() { // 获取模板信息
            if (!this.port.d || !this.port.team) {
                var msg = `错误信息: 缺少参数; 参数: TemplateNumber:${this.port.d},TeamNum:${this.port.team}`
                alert(msg)
                return
            }
            let params = `${this.designModel ? 'DocumentNumber' : 'TemplateNumber'}=${this.port.d}&TeamNum=${this.port.team}`;
            let url = this.designModel ? '/Document' : '/Template'
            this.$axios.post(url, params, {
                    headers: {
                        token: this.port.token
                    }
                })
                .then(({
                    data
                }) => {
                    // console.log(data)
                    this.templateInfo = data;
                    // alert(`模板信息: ${JSON.stringify(data)}`)
                    let key = this.designModel ? 'Pages' : 'TemplatePages'
                    // alert('下一步是查询json数据')
                    this.getPageJson(this.templateInfo[key]).then(arr => {
                        // console.log(this.templateInfo)
                        this.pages = this.templateInfo[key]
                        this.readerTemplate(this.pages[0].JsonContent)
                        this.productSVGHtml();
                    })
                })
                .catch((err) => {
                    alert('查询出错')
                })
        },
        getFontList() {
            // 获取字体列表
            this.$axios.get("/Fonts").then(({
                data
            }) => {
                this.familyList = data;
            });
        },
        colorCanvas() { // 绘制色板
            let canvas = this.$refs.canvas, w = 690, h = 90;
            let ctx = canvas.getContext('2d');
            var linearGradient= ctx.createLinearGradient(0,0,w,h);
            linearGradient.addColorStop(0,"#f0f")
            //添加渐变颜色
            ctx.fillStyle=linearGradient;
            ctx.fillRect(0,0,w,h) 
            // ctx.beginPath();

            var linearGradient2 = ctx.createLinearGradient(0,0,w,h);
            linearGradient2.addColorStop(0,"#fff")
            linearGradient2.addColorStop(1,"#000")
            //添加渐变颜色
            ctx.fillStyle=linearGradient2;
            ctx.fillRect(0,0,w,h) 

            var linearGradient3 = ctx.createLinearGradient(0,h/2,w,h/2);
            linearGradient3.addColorStop(0,"#fff")
            linearGradient3.addColorStop(1,"#000")
            //添加渐变颜色
            ctx.fillStyle=linearGradient3;
            ctx.fillRect(0,h/2,w,h/2) 

        },
        getFontThumb(font) { //获取当前字体名称
            let fontObj = '';
            for (let i = 0, len = this.familyList.length; i < len; i++) {
                // console.log(font , this.familyList[i].FontCairoName)
                if (font == this.familyList[i].FontCairoName) {
                    fontObj = this.familyList[i]
                    return fontObj;
                }
            }

            if (fontObj == '') fontObj = this.familyList[0]
            return fontObj
        },
        // 对话框toggle
        openDialogModel(msg) {
            this.dialogOpen = !this.dialogOpen;
            switch (msg) {
                case 'yes':
                    if (this.toolType == 'text') {
                        this.changeTextContent();
                    } else {
                        this.addText();

                    }
                    break;
                case 'change':
                    this.addTextContent = this.activeTextContent;
                    break;
            }
        },
        //背景颜色图片切换
        toggleBackground() {
            this.bgToggle = !this.bgToggle;
        },
        toggleTextType(msg) {
            this.textToggle = msg;
        },
        canvasInit() { // svg初始化
            if (this.draw) this.draw.remove();
            let editorSvg = this.$refs.editorSvg,
                drawing = this.$refs.drawing;
            // console.log(this.draw)
            // 获取显示区域的宽高
            let width = editorSvg.offsetWidth,
                height = editorSvg.offsetHeight;
            let w = 0,
                h = 0,
                eleid = "canvas",
                vw = 0,
                vh = 0;
            let size = this.templateInfo.Size;
            let ratio = size.Height / size.Width;
            if (size.Width >= size.Height) {
                w = width - 40;
                h = w * ratio;
                vw = 20;
                vh = (height - h) / 2;
            } else {
                h = height - 40;
                w = h / ratio;
                vh = 20;
                vw = (width - w) / 2;
            }
            drawing['style']['left'] = vw + 'px'
            drawing['style']['top'] = vh + 'px'
            drawing['style']['width'] = w + 'px'
            drawing['style']['height'] = h + 'px'
            let draw = SVG("drawing"),
                dpi = size.Unit == 'mm' ? ((size.ResolvingPower || 300) / 25.4) : 1;
            draw.size(w, h).viewbox(0, 0, size.Width * dpi, size.Height * dpi).attr("id", eleid);
            this.draw = draw;
        },
        
        getPageJson(page) { // 获取所有页面的jsoncontent
            return Promise.all(Array.from(page).map((p, index) => {
                return new Promise(resolve => {
                    fetch(this.port.ossPath + p.JsonPath + '?v=' + new Date().getTime())
                        .then(response => response.json())
                        .then(data => {
                            // alert(JSON.stringify(data))
                            p.JsonContent = data;
                            resolve(true)
                        })
                        .catch(err => {
                            alert(`获取json,返回错误${err}`)
                        })
                    // this.$axios.get(this.port.ossPath + p.JsonPath + '?v=' + new Date().getTime())
                    //     .then(({
                    //         data
                    //     }) => {
                    //         alert(JSON.stringify(data))
                    //         p.JsonContent = data;
                    //         resolve(true)
                    //     })
                    //     .catch(err => {
                    //         alert(`返回错误${err}`)
                    //     })
                })
            }))
        },
        readerTemplate(temaplate) { // 渲染svg到画布
            // console.log(temaplate, '页面数据')
            this.canvasInit();
            var masking = null;
            temaplate.forEach((item, i) => {
                item.eleid = new Date().getTime() + i;
                if (item.type != 'Masking') {
                    let firstGroup = this.draw.group(),
                        twoGroup = firstGroup.group(),
                        svgGroup = twoGroup.nested();
                    firstGroup.attr({
                        transform: item.transform,
                        id: item.eleid,
                        class: item.className,
                        opacity: item.opacity
                    }).data({
                        type: item.type,
                        obj: item.key,
                        group: item.group
                    })
                    if (item.type == 'background') {
                    } else if (item.type == 'adsorb') {
                    } else {
                        firstGroup.on("click", () => this.handleActive(item.eleid))
                    };

                    if (item.className == "hoveMove" && item.group == '') {
                    }
                    twoGroup.data({
                        rotate: item.rotate
                    }).attr('transform', item.rotation);
                    svgGroup.size(item.width, item.height).attr({
                        'viewBox': item.viewbox,
                        preserveAspectRatio: 'none'
                    }).style('overflow', '')
                    if (item.type == 'text') {
                        // console.log(item._html, 123)
                        let reg = /(fill|stroke)=rgb\(.*?\)/ig;
                        let reg2 = /fill="rgb\(0," 0,="" 0\)="" stroke="rgb\(0,"/g
                        let reg3 = /fill="rgb\(255," 255,="" 255\)="" stroke="rgb\(255,"/g
                        let reg4 = /fill="rgb\(112," 112,="" 112\)="" stroke="rgb\(112,"/g
                        item._html = item._html.replace(reg, function (val) {
                            let arr = val.split('=')
                            val = arr[0] + '="' + arr[1] + '"'
                            return val
                        })
                        item._html = item._html.replace(reg2, 'fill="#000" stroke="#000"')
                        item._html = item._html.replace(reg3, 'fill="#fff" stroke="#fff"')
                        item._html = item._html.replace(reg4, 'fill="#707070" stroke="#707070"')
                        item._html = item._html.replace(/(stroke-linecap=('|")round('|")|stroke-linejoin=('|")round('|"))/ig, '')
                        // console.log(item._html, 456)
                    }
                    svgGroup.svg(item._html || item.str)
                    if (item.type == undefined) firstGroup.remove();
                } else {
                    masking = item._html
                }
                if(masking) {
                    let size = this.templateInfo.Size
                    let dpi = size.Unit == 'mm' ? ((size.ResolvingPower || 300) / 25.4) : 1;
                    let str = `<svg width="${size.Width * dpi}" height="${size.Height * dpi}" preserveAspectRatio="none"`
                    this.model = this.draw.group()
                    this.model.style('pointer-events', 'none').data('type', 'Masking')
                    masking = masking.replace(/<svg?/, str)
                    this.model.svg(masking)
                }
            })
        },
        getLastChild() { // 获取最后一个元素
			let last = this.draw.last();
			if (last.type == 'defs') {
				last.remove()
				last = this.draw.last()
			}
			if (last.data('type') == 'Masking') 
				last = last.previous();
			return last
		},
		moveMaking() { // 保持刀版在最上一层
			let last = this.getLastChild();
			if (last && this.model) last.after(this.model);
		},
        getSvgHtml(obj) { // 根据JsonContent 生成svg Html
            // console.log(obj)
            let size = this.templateInfo.Size,
                masking = false,
                masking_html = '';
            let dpi = size.Unit == 'mm' ? ((size.ResolvingPower || 300) / 25.4) : 1,
                width = size.Width * dpi,
                height = size.Height * dpi;
            let _html = `<svg width="${200}" height="${200 * (size.Height / size.Width)}" 
				viewBox="0 0 ${width} ${height}"
				${this.templateInfo.TypeId != 23 ? 'style="background:#fff"' : ''}
				xmlns="http://www.w3.org/2000/svg" 
				version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">`
            obj.forEach(json => {
                if (json.type != 'Masking') {
                    if (json.type == 'text') {
                        let reg = /(fill|stroke)=rgb\(.*?\)/ig;
                        json._html = json._html.replace(reg, function (val) {
                            let arr = val.split('=')
                            val = arr[0] + '="' + arr[1] + '"'
                            return val
                        })
                        json._html.replace(/(stroke-linecap="round"|stroke-linejoin="round")/ig, '')
                    }
                    _html += `<g ${json.transform ? 'transform="' + json.transform + '"': ''} opacity="${json.opacity || 1}">
							<g ${json.rotation ? 'transform="' + json.rotation + '"': ''}>
								<svg width="${json.width}" height="${json.height}" 
								${json.viewbox ? 'viewBox="' + json.viewbox + '"': ''}
								preserveAspectRatio="none"
								xmlns="http://www.w3.org/2000/svg" 
								version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
									${json._html || ''}
								</svg>
							</g>
						</g>`
                } else {
                    masking = true;
                    masking_html = json._html || '';
                }
            })
            // if((this.templateInfo.ProductType.TypeId == 38 && this.templateInfo.Size.ID == 91) || this.templateInfo.ProductType.TypeId == 42)  {
            // 	_html += `
            // 		<g style="pointer-events: none;">
            // 			${masking_html}
            // 		</g>
            // 	`
            // } else if (this.templateInfo.Size.MaskingContent) {
            // 	_html += `
            // 		<g style="pointer-events: none;">
            // 			${this.templateInfo.Size.MaskingContent}
            // 		</g>
            // 	`
            // }

            _html += '</svg>'
            _html = _html.replace(/(http:|https:)*\/\/img.aliyin.com/g, 'http://img.aliyin.com')
            _html = _html.replace(/<g id="outBloodLine">.*?<\/g>/, '')
            _html = _html.replace(/<path id="outBloodLine".*?<\/path>/, '')
            return _html
        },
        productSVGHtml() { // 生成svgcontent
            this.pages.forEach(p => {
                p.SvgContent = this.getSvgHtml(p.JsonContent)
            })
        },
        /**
         * 激活当前选中容器，使之具备功能
         * @param {[type]} id
         */
        handleActive(id) {
            let group = SVG.get(id);
            if (group == null || group.node.children.length <= 0 || group.data("type") == "background") return;
            // let GroupSet = group.data('group') || ''
            // if (GroupSet != '') {
            //     this.getGroupAttr(group)
            //     return
            // };
            this.elementChecked = group;

            this.getSingleSvg(group); // 初始化box的大小和位置
            // 检测是否锁定
            // if (group.hasClass("hoveMove")) {
            //     this.svgLock = false
            //     this.getAllElemPos(); // 获取所有元素的位置
            // } else {
            //     this.svgLock = true
            // }
            // 根据类型绑定事件
            let type = group.data("type");
            let zoom = this.draw.viewbox().zoom;

            switch (type) {
                case "image":
                    this.toolType = "image";
                    let img = group.node.querySelector('image')
                    this.activeImg = img.getAttribute('xlink:href') || img.getAttribute('href')
                    // this.threeGroup = this.svgParent.first()
                    // this.codeTypeTool = '';
                    break;
                case "svg":
                    this.toolType = "svg";
                    this.getSvgFillList(group);
                    // this.threeGroup = this.svgParent.last()
                    // if (this.threeGroup.type == 'defs') {
                    //     this.threeGroup.remove();
                    //     this.threeGroup = this.svgParent.last()
                    // }
                    // this.handleSvgFill();
                    // this.codeTypeTool = '';
                    break;
                case "text":
                    this.toolType = "text";
                    this.textObj = group.data('obj');
                    this.RGBA[0] = this.textObj.fill || '#000';
                    this.textSize = parseInt(this.textObj.size);

                    if (typeof this.textObj.arrList != 'object') {
                        this.textObj.arrList = [this.textObj.arrList.replace(/(^\[)|(\]$)/g, "")]
                        let obj = JSON.parse(JSON.stringify(this.textObj))
                        group.data({
                            obj
                        })
                    }
                    this.activeTextContent = this.textObj.arrList.join("\n");

                    if (!this.textObj.scale) {
                        this.textObj.scale = this.textObj.size / group.first().first().height();
                        let obj = JSON.parse(JSON.stringify(this.textObj))
                        group.data({
                            obj
                        })
                    }
                    console.log(this.textObj)
                    break;
                case 'adsorb':
                    this.toolType = 'adsorb';
                    // this.codeTypeTool = 'adsorb';
                    // this.threeGroup = this.svgParent.first();
                    break;
            }

            // 获取透明度
            // this.opacityValue = group.opacity() * 100;
        },
        getSingleSvg(group) { // 获取单个激活的元素的位置和大小
            let zoom = this.draw.viewbox().zoom,
                twoGroup = group.first(),
                svgParent = group.first().first(),
                box = group.rbox(this.draw),
                bbox = group.bbox();
            this.codeBox.x = (box.x - bbox.x) * zoom;
            this.codeBox.y = (box.y - bbox.y) * zoom;
            this.codeBox.width = svgParent.width() * zoom;
            this.codeBox.height = svgParent.height() * zoom;
            this.codeBox.rotate = twoGroup.data("rotate") || 0;
            this.codeBox.isShow = true
            // this.setCursorStyle(this.codeBox.rotate)
            // console.log(box)
        },

        handleRecord(e) { // 记录坐标
            e.preventDefault();
            let classList = e.currentTarget.classList;
            if (e.touches.length == 1) {
                let rbox = this.elementChecked.rbox();
                this.record = {
                    ox: e.touches[0].pageX,
                    oy: e.touches[0].pageY,
                    bias: Math.sqrt((Math.pow(this.codeBox.width, 2) + Math.pow(this.codeBox.height, 2))),
                    size: classList.contains("rb") ? true : false,
                    rotation: classList.contains("lb") ? true : false,
                    transformedRect: getTransform(this.codeBox, this.codeBox.rotate),
                    cx: rbox.cx,
                    cy: rbox.cy
                }
                // console.log(this.record.ox, this.record.oy)
                this.recordCodeBox = JSON.parse(JSON.stringify(this.codeBox))
                document.addEventListener('touchmove', this.handleMove, false)
                document.addEventListener('touchend', this.handleEnd)
                let pointAndOpposite = getPointAndOpposite(this.record.transformedRect.point, this.record.ox, this.record.oy)
                // console.log(pointAndOpposite.opposite)

            }

        },
        handleMove(e) { //手指滑动
            // e.preventDefault();
            if (e.touches.length == 1) {
                let x = 0,
                    y = 0,
                    w = 0,
                    h = 0,
                    z = 1;
                let pageX = e.touches[0].pageX,
                    pageY = e.touches[0].pageY;
                if (this.record.size) {
                    w = this.recordCodeBox.width + (pageX - this.record.ox)
                    h = this.recordCodeBox.height + (pageY - this.record.oy)
                    z = Math.sqrt((Math.pow(w, 2) + Math.pow(h, 2))) / this.record.bias

                    // console.log(w, h)
                    return this.setCodeBoxDrag({
                        z: z
                    })
                } else if (this.record.rotation) {

                    let rotate = (Math.atan2(pageX - this.record.cx, this.record.cy - pageY) / Math.PI) * 180;
                    return this.setCodeBoxDrag({
                        rotate: Math.round(rotate + 135)
                    })
                } else {
                    x = pageX - this.record.ox;
                    y = pageY - this.record.oy;
                    return this.setCodeBoxDrag({
                        x,
                        y
                    })
                }
            }
        },
        handleEnd() { // 手指离开
            document.removeEventListener('touchmove', this.handleMove)
            document.removeEventListener('touchend', this.handleEnd)
        },
        setCodeBoxDrag({
            x,
            y,
            z,
            rotate
        }) { // 设置codeBox
            let zoom = this.draw.viewbox().zoom;
            // console.log(this.recordCodeBox)
            if (z) {
                this.codeBox.width = this.recordCodeBox.width * z;
                this.codeBox.height = this.recordCodeBox.height * z;

                if (this.codeBox.rotate) {
                    let newRect = getNewRect(this.recordCodeBox, {
                        x: z,
                        y: z
                    }, this.record.transformedRect, 0)
                    // console.log(newRect, this.codeBox.x)
                    this.codeBox.x = newRect.x;
                    this.codeBox.y = newRect.y;
                }
                this.elementChecked.get(0).get(0).size(Math.abs(this.codeBox.width / zoom), Math.abs(this.codeBox.height / zoom));
            } else if (rotate) {
                this.codeBox.rotate = rotate;
            } else {
                this.codeBox.x = this.recordCodeBox.x + x;
                this.codeBox.y = this.recordCodeBox.y + y;
            }
            this.elementChecked.get(0).attr("transform", `rotate(${this.codeBox.rotate},${this.codeBox.width / zoom / 2},${this.codeBox.height / zoom / 2})`).data({
                rotate: this.codeBox.rotate
            });
            this.elementChecked.move(this.codeBox.x / zoom, this.codeBox.y / zoom)

            if (this.toolType == "text") {
                let obj = this.elementChecked.data("obj");
                this.textObj.size = this.codeBox.height * obj.scale
                obj.size = this.textObj.size / zoom
                this.textSize = parseInt(obj.size);
                this.elementChecked.data({obj})
			}
        },
        handleClear() { // 清除画布控件
            this.isConfirm(false);
            this.toolType = 'all';
            this.codeBox.isShow = false;
            this.textToggle = 'content';
            this.replaceImg = false;
            this.operationType = ''; // 清除替换指令
            this.oldimg.old = ''; // 清除旧元素属性
        },
        handleTogglePage(i) { //切换页面
            let index = this.pageNum;
            let {str , list } = this.productJsonContent();
            this.pages[index].JsonContent = list;
            this.pages[index].SvgContent = str;

            this.pageNum = i;
            this.readerTemplate(this.pages[i].JsonContent)
        },
        /**初始化 创建元素容器
         * @return {Object} first, two, nested, three 创建的元素
         */
        nodeInit() {
            let first = this.draw.group(),
                two = first.group(),
                nested = two.nested(),
                three = nested.group(),
                id = new Date().getTime();
            first.id(id).addClass('hoveMove')
                .on('click', () => this.handleActive(id))
            two.data('rotate', 0)
            nested.node.removeAttribute('style')
            return {
                first,
                two,
                nested,
                three
            }
        },
        // 后台生成path方法
        productPath(obj) {
            return new Promise(resolve => {
                this.$axios.post(this.port.nodeUrl + "/textToPath/pro", obj)
                    .then(({
                        data
                    }) => {
                        resolve(data);
                    }).catch(err => {
                        resolve()
                    })
            })
        },
        addText() { // 添加文字
            // console.log(this.addTextContent.split('\n'))
            if (!this.addTextContent) return;
            this.textToPath()
        },
        textToPath(size = 30, data) { // 通过文字生成path
            let zoom = this.draw.viewbox().zoom,
                dbox = this.draw.rbox(this.draw);
            let obj = {
                family: this.familyList[0].FontName || '思源黑体-常规',
                fontId: 0,
                align: 'left',
                size: size / zoom,
                width: (data && data.width) || (200 / zoom),
                arrList: this.addTextContent.split('\n'),
                bold: 0,
                itailic: 0,
                underline: 0,
                spacing: 0,
                line: 1.2,
                fill: '#000',
                scale: 1
            }
            let {
                first,
                two,
                nested,
                three
            } = this.nodeInit();
            first.data({
                type: 'text',
                obj: obj
            })
            nested.size(obj.width, obj.size)
                .viewbox(0, 0, obj.width, obj.size)
            first.center(dbox.cx - obj.width / 2, dbox.cy - obj.size / 2);
            this.handleActive(first.id())
            this.productPath(obj).then(result => {
                if (!result) { // 生成失败时,删除
                    first.remove();
                    this.codeBox.isShow = false;
                    return
                }
                let str = result.svg,
                    width = result.width,
                    fourGroup = three.group(),
                    rect = nested.rect('100%', '100%').opacity(0);
                three.before(rect);
                three.attr({
                    fill: '#000',
                    stroke: '#000'
                });

                fourGroup.svg(str)
                let threebox = fourGroup.bbox();
                fourGroup.y(-threebox.y)

                obj.scale = obj.size / threebox.height;
                let ratio = threebox.height / width;
                first.data({
                    obj: obj
                })

                nested.size(width, threebox.height)
                    .viewbox(0, 0, width, threebox.height).data({
                        ratio
                    })
                this.handleActive(first.id())
                this.moveMaking()
            })
        },
        changPath(result, elem, obj) { // 生成文字后续操作
            let zoom = this.draw.viewbox().zoom,
                twoGroup = elem.first(),
                parent = twoGroup.first(),
                threeGroup = parent.last(),
                rotate = twoGroup.data('rotate'),
                data = elem.data('obj'),
                width = result.width;
            if (data.itailic) width += 10;
            threeGroup.clear()
            let fourGroup = threeGroup.group();
            fourGroup.svg(result.svg);
            let resgroup = this.draw.group().svg(result.svg),
                resbox = resgroup.bbox(),
                height = resbox.height;
            fourGroup.y(-resbox.y);
            resgroup.remove();

            let ratio = height / width;
            parent.data({
                ratio: ratio
            });
            twoGroup.attr('transform', `rotate(${rotate},${width / 2},${height / 2})`)
            parent.size(width, height).viewbox(0, 0, width, height);
            this.codeBox.height = height * zoom;
            data.scale = data.size / height;
            elem.data({
                obj: data
            })
            this.handleActive(elem.id())
        },
        changeTextContent() { // 改变选中的文字
            let obj = this.elementChecked.data('obj')
            obj.arrList = this.addTextContent.split('\n')
            let elem = this.elementChecked;
            this.elementChecked.data({
                obj
            })
            this.productPath(obj).then(result => {
                this.changPath(result, elem, obj)
            })
        },
        changeTextFamily(i) { // 改变选中文字的字体
            let obj = this.elementChecked.data('obj');
            obj.family = this.familyList[i].FontName;
            let elem = this.elementChecked;
            this.elementChecked.data({
                obj
            })
            this.productPath(obj).then(result => {
                this.changPath(result, elem, obj)
            })
        },
        changeTextColor(color) { // 改变选中文字的颜色

            let childs = this.elementChecked.first().first().children(),
                threeGroup;
            for (let i = 0; i < childs.length; i++) {
                if (childs[i].type == 'g') {
                    threeGroup = childs[i]
                    break;
                }
            }
            this.textObj.fill = threeGroup.attr('fill');
            this.textObj.newFill = color;
            threeGroup.fill(color).stroke(color)

        },
        changeTextSize() { // 改变选中文字大小
            let obj = this.elementChecked.data('obj');
            obj.size = this.textSize;
            let elem = this.elementChecked;
            this.elementChecked.data({
                obj
            })
            this.productPath(obj).then(result => {
                this.changPath(result, elem, obj)
            })
        },
        changeTextAlign(align) { // 改变文字的对齐方式
            let obj = this.elementChecked.data('obj');
            obj.align = align;
            let elem = this.elementChecked;
            this.elementChecked.data({
                obj
            })
            this.productPath(obj).then(result => {
                this.changPath(result, elem, obj)
            })
        },
        changeTextStyle(style) { // 改变选中文字的样式
            this.textObj[style] = this.textObj[style] == 1 ? 0 : 1;
            let obj = this.elementChecked.data("obj");
            obj[style] = this.textObj[style];
            let elem = this.elementChecked;
            this.elementChecked.data({
                obj
            })
            this.productPath(obj).then(result => {
                this.changPath(result, elem, obj)
            })
        },
        changeTextBlod() { // 改变文字粗体
            this.textObj.bold = this.textObj.bold == 2 ? 0 : 2;
            let obj = this.elementChecked.data('obj');
            obj.bold = this.textObj.bold;
            let elem = this.elementChecked;
            this.elementChecked.data({
                obj
            })
            this.productPath(obj).then(result => {
                this.changPath(result, elem, obj)
            })
        },
        isConfirm(type) { // 文字的确定和取消
            switch (this.textToggle) {
                case "lock":
                    break;
                case "content":
                    break;
                case "font":
                    break;
                case "color":
                    if (type) {
                        let obj = this.elementChecked.data('obj');
                        obj.fill = this.textObj.newFill;
                        this.elementChecked.data({
                            obj
                        })
                    } else {
                        this.changeTextColor(this.textObj.fill)
                    }
                    break;
                case "size":
                    break;
                case "align":
                    break;
                case "style":
                    break;
            }
            switch (this.toolType) {
                case 'bg':
                    if (type) {
                        this.oldElemt.bg.old && (this.oldElemt.bg.old.remove())
                    } else {
                        this.oldElemt.bg.old && (this.oldElemt.bg.old.style('display', 'block'))
                        this.oldElemt.bg.replace && (this.oldElemt.bg.replace.remove())
                        
                        // this.handleSave();
                    }
                    this.oldElemt.bg.old = null;
                    this.oldElemt.bg.replace = null;
                    this.toolType = 'all';

                    break;
                case 'text':
                    this.codeBox.isShow = false;
                    this.textToggle = 'content';
                    this.toolType = 'all';
                break;
            }

        },
        getMaterialTypes() { // 获取图片素材的分类
            this.$axios.get('/MaterialTypes')
                .then(({
                    data
                }) => {
                    this.materialTypes = data;
                    this.matterParams.TypeNum = data[0].Num
                    this.getMatterList().then(data => {
                        data && (this.materialTypesList = data.Data);
                    })
                })
        },
        changeMaterialTypes(item, index) {
            this.materialTypesIndex = index;
            this.matterParams.TypeNum = item.Num;
            this.matterParams.pageIndex = 1;
            this.getMatterList().then(data => {
                this.$refs.imgList.scrollLeft = 0;
                data && (this.materialTypesList = data.Data);
            })
        },
        getMatterList() { // 获取分类素材列表
            return new Promise(resolve => {
                let url = '/MaterialInfos' + `?TypeNum=${this.matterParams.TypeNum}&TypeCategoryNum=${  this.matterParams.TypeCategoryNum  }&pageIndex=${this.matterParams.pageIndex}&pageSize=${ this.matterParams.pageSize }&KeyWords=`;
                this.$axios.get(url)
                    .then(({
                        data
                    }) => {
                        try {
                            data = JSON.parse(data)
                        } catch (error) {
                            data = false
                        }
                        resolve(data)
                    })
                    .catch(err => resolve(false))
            })
        },
        changeScroll(e) { // 加载更多
            if (!this.matterParams.more) return;
            let ele = e.currentTarget;
            if (ele.clientWidth + ele.scrollLeft > ele.scrollWidth - 20) {
                this.matterParams.pageIndex++;
                this.matterParams.more = false;
                this.getMatterList().then(data => {
                    this.matterParams.more = true
                    data && (this.materialTypesList = [].concat(this.materialTypesList, data.Data));
                })
            }
        },
        handleImgLoad(e , src, i) {
        
            let type = src.indexOf('.svg') > -1 ? true : false;
            let index = i;
            console.log(type)
            if (type) {
                let ele = e.target;
                this.$axios.get(src).then(({data}) => {
                    // this.materialTypesList[index].Svgtext = data;
                    ele.onclick = () => this.addSvg(data, src)
                })
            }
            
        },
        handleReplace() { // 替换图片
            this.replaceImg = true;
            this.operationType = 'replaceImg';
        },
        addImage(src, add = true) { // 添加图片
            src = src + (src.indexOf('.svg') > -1 ? '' : '!w280.src')
            let type = src.indexOf('.svg') > -1 ? false : true;
            if (type) { // 不是svg添加图片
                if (!add) { // 替换
                    let svg = this.elementChecked.first().first();
                    let image = svg.first().first();
                    if (!this.oldimg.old) {
                        this.oldimg.old = image.attr('xlink:href');
                    }
                   
                    let oldw = svg.width();
                    image.load(src).loaded(load => {
                        let h = oldw / load.ratio
                        image.size(oldw, h)
                        svg.size(oldw, h).viewbox(0, 0, oldw, h)
                        this.handleActive(this.elementChecked.id())
                    })
    
                } else { // 添加
                    let {
                        first,
                        two,
                        nested,
                        three
                    } = this.nodeInit();
                    first.data({
                            type: "image"
                        }).attr({
                            "id": new Date().getTime(),
                            class: 'hoveMove',
                        }).data({
                            obj: {
                                src: src
                            }
                        })
                        .on("click", () => this.handleActive(first.id()))
                    two.data('rotate', 0)
                    let image = three.image(src).loaded(load => {
                        let ratio = load.height / load.width;
                        let dbox = this.draw.rbox(this.draw);
                        let w = this.draw.width() * .2 / (this.draw.viewbox().zoom);
                        image.size(w, w * ratio);
                        nested.size(w, w * ratio).viewbox(0, 0, w, w * ratio).attr({
                            "preserveAspectRatio": "none",
                            style: ''
                        }).data({
                            ratio: ratio
                        });
                        first.move(dbox.cx - w / 2, dbox.cy - w * ratio / 2)
                        this.handleActive(first.id())
                    })
                    this.addList.push(first)
                }
                this.moveMaking()
            } 
        },
        addSvg(str, src) { // 添加svg
            console.log('这是svg')
            let {
                first,
                two,
                nested,
                three
            } = this.nodeInit();
            first.data({
                type: "svg"
            }).attr({
                "id": new Date().getTime(),
                class: 'hoveMove',
            }).data({
                obj: {src: src}
            })
            .on("click", () => this.handleActive(first.id()))
			two.data('rotate', 0)
			nested.style('overflow', '')
            three.svg(str)
            let dbox = this.draw.rbox(this.draw);
			let gbox = first.rbox(this.draw);
			let ratio = (gbox.height || 15) / (gbox.width || 15);
			let w = this.draw.width() * .2 / (this.draw.viewbox().zoom);
			nested.size(w, w * ratio).viewbox(0, 0, w, w * ratio).attr("preserveAspectRatio", "none").data({
				ratio: ratio
			})
			let rect = nested.rect('100%', '100%').opacity(0)
			three.before(rect)
            first.center(dbox.cx, dbox.cy )
            this.handleActive(first.id())
            this.addList.push(first)
        },
        getSvgFillList(first) { // 拾取选中svg的颜色列表
            let _html = first.node.outerHTML, colorList = [];
            let reg = /(#.*?(;|")|rgba?\(.*?\))/ig,
				arr = _html.match(reg);
				arr && arr.forEach(color => {
					color = color.replace(/;|"/ig, '')
					if (colorList.indexOf(color) < 0) {
						colorList.push(color)
					}
                })
            this.svgFillList = colorList;
        },
        handleSelectSvg(i) { // 选中svg颜色列表下标
            this.svgFillIndex = i;
        },
        setSvgFill(color) { // 设置svg颜色
            let _html = this.elementChecked.node.innerHTML;
            let reg = this.svgFillList[this.svgFillIndex];
            _html = _html.replace(reg, color);
            this.svgFillList[this.svgFillIndex] = color;
            this.elementChecked.node.innerHTML = _html;
        },
        getBgList() { // 获取背景图片列表
            return new Promise((resolve) => {
                let url = `/MaterialInfos?TypeNum=11&TypeCategoryNum=0&pageIndex=${this.bgparams.pageIndex}&pageSize=${this.bgparams.pageSize}`
                this.$axios.get(url)
                    .then(({
                        data
                    }) => {
                        try {
                            data = JSON.parse(data)
                        } catch (error) {
                            data = false
                        }
                        resolve(data)
                        // console.log(data)
                    })
                    .catch(err => resolve(false))
            })
        },
        getMoreBg(e) { // 背景图片加载更多
            if (!this.bgparams.more) return;
            let ele = e.currentTarget;
            if (ele.clientWidth + ele.scrollLeft >= ele.scrollWidth - 20) {
                this.bgparams.pageIndex++;
                this.bgparams.more = false;
                this.getBgList().then(data => {
                    this.bgparams.more = true;
                    data && (this.bgImages = [].concat(this.bgImages, data.Data))
                })
            }
        },
        changeBg(src, color) { // 更换背景图片
            src = src + (src.indexOf('.svg') > -1 ? '' : '!w280.src');
            this.oldElemt.bg.old && (this.oldElemt.bg.old.style('display', 'none'))

            let {
                first,
                two,
                nested,
                three
            } = this.nodeInit(), viewbox = this.draw.viewbox();
            first.data({
                type: 'background'
            });
            this.draw.first().before(first)
            if (src) {

                three.image(src).loaded(load => {
                    let ratio = load.height / load.width;
                    let w = null,
                        h = null;
                    if (load.height < viewbox.height && load.width < viewbox.width || load.height > viewbox.height && load.width > viewbox.width) {
                        // 1. 加载图片比画布小 或都比画布大
                        // console.log('加载图片比画布小')
                        let _w = load.width / viewbox.width;
                        let _h = load.height / viewbox.height;
                        if (_w > _h) {
                            h = viewbox.height;
                            w = h / ratio
                        } else {
                            w = viewbox.width;
                            h = w * ratio;
                        }
                    } else {
                        // 3. 某一边比画布大
                        // console.log('某一边比画布大')
                        if (load.height > viewbox.height) {
                            w = viewbox.width;
                            h = w * ratio;
                        } else {
                            h = viewbox.height;
                            w = h / ratio;
                        }
                    }
                    nested.size(w, h);
                    nested.viewbox(0, 0, load.width, load.height);
                    nested.style("overflow", "").attr("preserveAspectRatio", "none");
                    first.center(this.draw.rbox(this.draw).cx, this.draw.rbox(this.draw).cy);
                    first.data({
                        obj: 'image'
                    })
                    this.oldElemt.bg.replace && (this.oldElemt.bg.replace.remove())
                    this.oldElemt.bg.replace = first;
                    this.moveMaking()
                })
            }
            if (color) {
                nested.size(viewbox.width, viewbox.height).viewbox(0, 0, viewbox.width, viewbox.height)
                three.rect('100%', '100%').fill(color);
                this.oldElemt.bg.replace && (this.oldElemt.bg.replace.remove())
                this.oldElemt.bg.replace = first;
            }
        },
        changeToolType(type) { // 选中某个元素的默认源对象
            if (!this.draw) return;
            switch (type) {
                case 'bg':
                    this.toolType = 'bg';
                    let child = this.draw.children();
                    for (let i = 0; i < child.length; i++) {
                        if (child[i].data('type') == 'background') {
                            this.oldElemt.bg.old = child[i];
                            // this.oldElemt.bg.style('display', 'none')
                            break;
                        }
                    }
                    break;
            }
        },
        handleDelete() { // 删除元素
            this.elementChecked && this.elementChecked.remove();
            this.handleClear();
        },
        handleClone() { // 复制元素
            if (this.elementChecked) {
                var clone = this.elementChecked.clone();
                clone.on("click", () => this.handleActive(clone.id()));
                clone.move(clone.x() + 20, clone.y() + 20)
                this.handleClear();
                console.log(clone.x())
            }
        },
        
        handleColor(type, color) { // 打开调色盘
            this.colorPicker.show = true
            this.colorPicker.type = type;
            this.colorPicker.color = color || '#745BFF'
        },
        colorConfirmChoice(ok) { // 确认选择
            switch(this.colorPicker.type) {
                case 'bg':
                    if (ok) {
                        this.changeBg('', this.colorPicker.color.hex)
                    } 
                break;
                case 'svg':
                    if (ok) {
                        this.setSvgFill(this.colorPicker.color.hex)
                    } 
                break; 
                case 'text':
                    if (ok) {
                        this.changeTextColor(this.colorPicker.color.hex)
                    }
                break;
            }
            
            this.colorPicker.show = false;
        },

        handleImage(type) { // 打开图片选择
            this.imgPicker.show = true;
            this.imgPicker.type = type;
        },
        chooseImage(src, i) { //图片的操作方式
            if (src.indexOf('.svg') !== -1) {
                return
            }
            console.log('这是图片')
            let add = this.imgPicker.type == 'add' ? true : false;
            if (add) {
                this.addImage(src)
            } else {
                this.addImage(src, add)
            }

        },
        imgConfirmChoice(ok) { // 图片确认选择
            switch(this.imgPicker.type) {
                case 'add':
                    if (ok) {
                        this.addList = []
                    } else {
                        this.addList.forEach(item => item.remove())
                        this.handleClear();
                    }
                    break;
                case 'replace':
                    break;
            }
            this.imgPicker.show = false;
            this.imgPicker.type = '';
        },

        uploadImage(type) { // 上传图片
            this.miniprogram().then(src => {
                this.$toast.clear();
                if (!src) return;
                switch(type) {
                    case 'bg':
                        this.changeBg(src)
                        break;
                    case 'img':
                        this.chooseImage(src)
                        break;
                }
                // console.log(src)
            })
        },

        productJsonContent() { // 生成jsoncontent
            let str, node ;
			// console.log(this.templateInfo.Size)
			node = this.draw.node.cloneNode(true);
			node = SVG(node)
			let ratio = this.templateInfo.Size.Height / this.templateInfo.Size.Width;
			node.size(400, 400 * ratio)
			str = node.svg();
			str = str.replace(/<g id="outBloodLine">.*?<\/g>/, '')
			str = str.replace(/<path id="outBloodLine".*?<\/path>/, '')
			str = str.replace(/(http:|https:)*\/\/img.aliyin.com/g, 'http://img.aliyin.com')
			// console.log(str)
			let childs = this.draw.children(),
				list = [];
			try {
				childs.forEach(child => {	
					let type = child.data('type'), eleAttr; 
					if (child.type == 'g' && type && type != 'Masking') {
						let twoGroup, svgGroup, threeGroup;
						twoGroup = child.first();
						svgGroup = twoGroup.first();
						threeGroup = svgGroup.last();
						if (threeGroup.type == 'defs') {
							threeGroup.remove();
							threeGroup = svgGroup.last();
						}
						eleAttr = {
							type,//类型
							eleid: child.attr('id'), // id
							transform: child.attr('transform'), // 位移数据
							className: child.attr("class"), // 类名信息
							opacity: child.attr('opacity') || 1, // 透明度
							key: child.data("obj") || "", // 关键属性
							rotate: twoGroup.data("rotate") || 0, // 旋转
							rotation: twoGroup.attr('transform'),
							width: svgGroup.width(), // 宽度
							height: svgGroup.height(), // 高度
							viewbox: svgGroup.attr('viewBox'),
							reverce: threeGroup.attr('transform'), // 翻转
							_html: svgGroup.node.innerHTML, // 最核心svg内容
							group: child.data('group') || '', // 组合标识信息
							"group-transform": "" // 组合变换数据
						}
						// 需要带数据结构的数组
						// console.log(eleAttr)
						
					} else if (type == 'Masking') {
						eleAttr = {
							type,
							_html: child.node.innerHTML
						}
					}
					eleAttr && list.push(eleAttr);
				});
				
			} catch (err) {
				console.log(err);
			}
			// list = JSON.stringify(list); // 转换为json存储
			
			return { str, list };
        },

        handleSave() { // 单个页面保存
            let index = this.pageNum;
            let {str, list} = this.productJsonContent();
            this.pages[index].JsonContent = list;
            this.pages[index].SvgContent = str;
            this.redoList.push(list)
        },
        // 生成缩略图
		productThumbnail(item, index) {
			if (!index) index = ''
			return new Promise((resolve, reject) => {
				let data = {
					svg: item.SvgContent,
					name: new Date().getTime() + index,
					width: 800
                };
				this.$axios.post(this.port.productThumbnail, data)
				.then(({data}) => {
					let url = data.path;
                    // 返回URL
                    // this.errMsg.push('node 返回的图片地址:' + url + ';' )
					resolve(url);
                })
                .catch(err => {
                    // this.errMsg.push('生成图片出错了:' + err + ';' )
                    resolve('')
                })
				
			})
        },
        updateTemplate() { // 更新模板数据
            Promise.all(Array.from(this.pages).map((item, i) => {
                return new Promise((resolve, reject) => {
                    this.productThumbnail(item, i)
                    .then(img => {
                        // console.log(item)
                        // this.errMsg.push('这是返回的缩略图:' + img + ';' )
                        if (img) {
                            item.Thumb = this.port.nodeUrl + img+ `?v=${new Date().getTime()}`;
                            item.ThumbPath = this.port.nodeUrl + img+ `?v=${new Date().getTime()}`;
                        }
                        if (typeof item.JsonContent === 'object') {
                            item.JsonContent = JSON.stringify(item.JsonContent)
                        }
                        this.$axios.put('/DocumentPage', item)
                        .then(({data}) => {
                            if (data.state = 'success') {
                                this.pages[i].Thumb = data.key
                                resolve(true)
                            }
                        })
                        .catch(err => resolve(err))
                    })
                })
            }))
            .then(arr => {
                this.$toast.clear();
                wx.miniProgram.navigateTo({
                    url: '../savepage/savepage?d=' + this.templateInfo.DocumentNumber
                })
                // this.saveTemplateBtn = true;
                this.designModel = true; // 模式改为更新
            })
            .catch(err => {
            })
        },
        saveTemplate() { // 保存模板
            
            let index = this.pageNum;
            let {str, list} = this.productJsonContent();
            this.pages[index].JsonContent = list;
            this.pages[index].SvgContent = str;
            var Pages = []
            this.pages.forEach(item => {
                Pages.push({
                    JsonContent: JSON.stringify(item.JsonContent),
                    SvgContent: item.SvgContent
                })
            })
            /**
             * 两种情况
             * 1.从其他非设计记录点进设计器,创建新的设计记录
             * 2. 从设计记录点进设计器,保存更新当前记录的数据
             */
            var data = {
                ProductCategorieNum: this.templateInfo.ProductType.FromClass,
                TypeId: this.templateInfo.TypeId,
                SizeId: this.templateInfo.SizeId,
                Name: '未命名',
                TeamNum: this.port.team,
                Pages
            };

            if(!this.designModel) {
                var toast = this.$toast({
                    type: 'loading',
                    mask:true,
                    loadingType: 'spinner',
                    duration: 0,
                    message: '创建模板中'
                });
                //第一种 , 创建
                this.$axios.post('/TeamTemplate', data)
                .then(({data}) => {
                    try{
                        data = JSON.parse(data)
                    }catch(err) {
                        data = false;
                    }
                    console.log(data)
                    if (!data) {
                        this.$notify('创建失败!');
                        return
                    }
                    data.Pages.forEach((item, index) => {
                        item.JsonContent = JSON.stringify(this.pages[index].JsonContent);
                        item.SvgContent = this.pages[index].SvgContent;
                    })
                    if (this.templateInfo.TemplateNumber) {
                        this.templateInfo.DocumentNumber = data.DocumentNumber
                    }
                    // this.templateInfo
                    this.pages = data.Pages
                    // console.log(this.pages)
                    toast.message = '保存中'
                    this.updateTemplate();
                    
                })
            } else {
               this.$toast({
                    type: 'loading',
                    mask:true,
                    loadingType: 'spinner',
                    duration: 0,
                    message: '保存中'
                });
                // 第二种, 更新
                this.updateTemplate();
            }

        },

        handleClip(type) { // 裁剪图片 
            
            if (type) {
                this.$refs.cropper.getCropBlob((blob) => {
                    // do something
                    // console.log(blob)  
                    this.$toast({
                        type: 'loading',
                        mask:true,
                        loadingType: 'spinner',
                        duration: 0,
                        message: '裁剪中'
                    });
                    console.log(blob)
                    this.ossUploadImage(blob).then(src => {
                        this.$toast.clear();
                        this.addImage(src, false);
                    })
                })
            } 
            this.clipImageBtn = false;
        },
        ossUploadImage(file) {// 上传图片到服务器
            return new Promise(resolve => {
                var formdata = new FormData();
                formdata.append('TeamNum', this.port.team || 17)
                formdata.append('TypeNum', 0)
                formdata.append('TypeCategoryNum', 0)
                formdata.append('IsPublic',0)
                formdata.append('file',file)
                this.$toast({
                    type: 'loading',
                    mask:true,
                    loadingType: 'spinner',
                    duration: 0,
                    message: '上传中'
                });
                this.$axios.post('/TeamMaterial', formdata)
                .then(({data}) => {
                    try{
                        data = JSON.parse(data)
                    } catch(e) {
                        data = ''
                    }
                    var src = '';
                    if (data) {
                        src = 'https:' + (data.url || data.svgurl)
                    }
                    resolve(src)
                })
                .catch(err => {
                    resolve('')
                })
            })
            
        },
        miniprogram() {// 上传图片到服务器
            const that = this;
            return new Promise(resolve => {
                wx.chooseImage({
                    count: 1,
                    sizeType: ['original', 'compressed'],
                    sourceType: ['album', 'camera'],
                    success(res) {
                        // tempFilePath可以作为img标签的src属性显示图片
                        var localIds = res.localIds;
                        wx.getLocalImgData({
                            localId: localIds[0].toString(), //仅为示例，非真实的接口地址
                            success: res => {
                                const localData = res.localData;
                                let imageBase64 = '';
                                if (localData.indexOf('data:image') == 0) {
                                  //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                                  imageBase64 = localData;
                                } else {
                                  //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                                  //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                                  imageBase64 = 'data:image/png;base64,' + localData.replace(/\n/g, '');
                                }
                                that.ossUploadImage(dataURLtoBlob(imageBase64)).then(src => {
                                    if(!src) {
                                        alert('上传失败')
                                    }
                                    resolve(src)
                                });
                            },
                        })
                    }
                })
            })
            
        },
        getwx() { // 配置微信小程序可使用api的权限
            var formdata = new FormData();
            formdata.append('url', location.href.split('#')[0])
            this.$axios.post('/wxjssdksign', formdata)
            .then(({data}) => {
                var config = data.result;
                // console.log(wx)
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: config.appId, // 必填，公众号的唯一标识
                    timestamp: Number(config.timestamp), // 必填，生成签名的时间戳
                    nonceStr: config.nonceStr, // 必填，生成签名的随机串
                    signature: config.signature,// 必填，签名
                    jsApiList: ['chooseImage', 'checkJsApi', 'getLocalImgData'] // 必填，需要使用的JS接口列表
                })
                wx.ready(() => {
                    console.log('配置成功')

                    
                })
                wx.error(function(res){
                    console.log(res, '配置出错')
                    // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                });

                wx.checkJsApi({
                    jsApiList: ['chooseImage'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
                    success: function(res) {
                        console.log(res)
                    // 以键值对的形式返回，可用的api值true，不可用为false
                    // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                    }
                });

            })
            
        },

        /**
         * 添加页面
         * @copy 是否为复制
         */
        addTemplatePage(copy) {

            console.log(this.pages, this.templateInfo)
            if (this.pages.length >= this.templateInfo.ProductType.MaxPages) {
                this.$notify({ type: 'warning', message: '页面已经达到最大数量了',duration: 2000 });
                return
            }
            if(copy) {
                let JsonContent = JSON.parse(JSON.stringify(this.pages[this.pageNum].JsonContent));
                let SvgContent = this.pages[this.pageNum].SvgContent;
                this.pageNum = this.pages.length;
                this.pages.push({
                    JsonContent,
                    SvgContent
                })
                this.canvasInit();
                this.readerTemplate(this.pages[this.pageNum].JsonContent)
            } else {
                console.log('重新渲染')
                this.handleSave();
                this.canvasInit();
                this.pageNum = this.pages.length;
                let {str, list} = this.productJsonContent();
                // console.log(str, list)
                this.pages.push({
                    JsonContent: list,
                    SvgContent: str
                })
            }
            
        },

        /**
         * 删除页面
         */
        deleteTemplatePage() {
            if (this.pages.length == 1) {
                this.$notify({ type: 'warning', message: '最后一页不能删除哦',duration: 2000 });
                return
            }
            this.$dialog.confirm({
                title: '提示',
                message: '是否确认删除,不可恢复'
              }).then(() => {
                // on confirm
                this.pages.splice(this.pageNum, 1)
                if(this.pageNum < this.pages.length) {
                    this.readerTemplate(this.pages[this.pageNum].JsonContent)
                } else {
                    this.pageNum--;
                    this.readerTemplate(this.pages[this.pageNum].JsonContent)
                }
            })
        },

        /**
         * 复制页面
         */
        copyTemplatePage() {
            if (this.pages.length >= this.templateInfo.ProductType.MaxPages) {
                this.$notify({ type: 'warning', message: '页面已经达到最大数量了',duration: 2000 });
                return
            }
            this.addTemplatePage(true)
        }
    },


};